package com.white.controller;

import com.white.bean.Comment;
import com.white.bean.Reply;
import com.white.service.CommentService;
import com.white.service.ReplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ReplyController {

    @Autowired
    CommentService commentService;
    @Autowired
    ReplyService replyService;

    @PostMapping("/reply")
    @ResponseBody
    public boolean reply(@RequestParam("articleId") Long articleId,
                         @CookieValue(UserController.LOGIN_USER_ID) Long userId,
                         @RequestParam("beReplyCommentId") Long beReplyCommentId,
                         @RequestParam("content") String content){
        return saveReply(articleId, userId, beReplyCommentId, content);
    }

    @PostMapping("/replyByCommentId")
    @ResponseBody
    public boolean replyByCommentId(@CookieValue(UserController.LOGIN_USER_ID) Long userId,
                                    @RequestParam("beReplyCommentId") Long beReplyCommentId,
                                    @RequestParam("content") String content){
        /*获取被回复的评论信息*/
        Comment beReplyComment = commentService.getById(beReplyCommentId);
        return saveReply(beReplyComment.getArticleId(), userId, beReplyCommentId, content);
    }


    /**
     * 保存回复信息
     * @param articleId 文章id
     * @param userId 用户id
     * @param beReplyCommentId 被回复评论信息
     * @param content 回复内容
     * @return
     */
    public boolean saveReply(@RequestParam("articleId") Long articleId,
                             @CookieValue(UserController.LOGIN_USER_ID) Long userId,
                             @RequestParam("beReplyCommentId") Long beReplyCommentId,
                             @RequestParam("content") String content){
        /*先保存评论*/
        Comment comment = new Comment(articleId, userId, content);
        try {
            if (!commentService.save(comment)) {
                return false;
            }
            /*查询评论id*/
            comment = commentService.getOne(comment);
            /*再保存回复*/
            Reply reply = new Reply(beReplyCommentId, comment.getCommentId());
            if (!replyService.save(reply)) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}
